package controller.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UserDao;
import factory.UserFactory;

@WebServlet("/modifyPwd")
public class ModifyPwdServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			UserDao userDao = UserFactory.getInstance("userdaoimpl", UserDao.class);
			String oldPwd = request.getParameter("uoldpwd");
			String newPwd = request.getParameter("unewpwd");
			String regex = "(?!([a-zA-Z]+|\\d+)$)[a-zA-Z\\d]{4,20}";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(newPwd);
			PrintWriter out = response.getWriter();
			if(!m.matches()) {
				out.println("<script>alert('密码格式错误，至少4位，含字母和数字！');history.back();</script>") ;
				return;
			}
			if(newPwd != null && !newPwd.trim().equals("")) {
				HttpSession session = request.getSession();
				String uname = (String)session.getAttribute("uname");
				int result = userDao.updateUserPwd(userDao.getAppointUser(uname), oldPwd, newPwd);
				if(result == 1) {
					request.getRequestDispatcher("view/index.jsp").forward(request, response);
				}else if(result == 0) {
					out.println("<script>alert('修改密码失败，旧密码输入错误！');history.back();</script>") ;
				}else {
					out.println("<script>alert('修改密码失败，服务器出错');history.back();</script>") ;
				}
			}else {
				out.println("<script>alert('新密码不能为空或者都是空格！');history.back();</script>") ;
			}
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}